﻿using Cysharp.Threading.Tasks;
using Data;
using Services.Loot;
using System;
using UnityEngine;

namespace Level.Decorations
{
    public class ObstacleDeath : MonoBehaviour
    {
        public event Action<int> Removed;

        [SerializeField] private Obstacle _obstacle;
        [SerializeField] private ObstacleHealth _health;
        private ILootService _lootService;
        private GameSceneData _data;

        public void Construct(GameSceneData data, ILootService lootService)
        {
            _lootService = lootService;
            _data = data;
        }

        private void Start() =>
            _health.Destroyed += OnObstacleDestroy;

        private void OnDestroy() =>
            _health.Destroyed -= OnObstacleDestroy;

        private async void OnObstacleDestroy()
        {
            await UniTask.Delay(TimeSpan.FromSeconds(_data.CreateAnimationTime));
            _data.Obstacles.Remove(_obstacle);
            Removed?.Invoke(_obstacle.Value);
            _lootService.GenerateLoot(_obstacle.Position);
            Destroy(gameObject);
        }
    }
}